import {
  AddReq,
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  CrudExpose,
  CrudOptions,
  DelReq,
  EditReq,
	dict,
	compute,
  useColumns,
  useFormWrapper,
  UserPageQuery,
  UserPageRes
} from "@fast-crud/fast-crud";
import * as api from './info.api';
import { dictionary } from '/@/utils/dictionary';
import { successMessage } from '../../../utils/message';
import { auth } from '/@/utils/authFunction';
import { ref, nextTick, computed } from 'vue';
import { ElMessage } from "element-plus";

const selectedIds = ref([]);

const medicine =  ref()

const onSelectionChange = (changed: any) => {
	console.log("selection", changed);
	selectedIds.value = changed
	const twoDimensionArr = selectedIds.value.map((item: any) => [item.code, {
		title: item.name,
		type: "number",
		form: {
			rules: [
				{
					required: true,
					message: "请输入药品数量",
					trigger: "blur",
				},
			],
		}
	}])
	console.log(twoDimensionArr);
	medicine.value = Object.fromEntries(new Map(([...twoDimensionArr] as [string, any][])))
	console.log(medicine.value);
};


function useBuyMedicineFormWrapper(crudExpose: CrudExpose) {
  let index = 0;
  // 自定义表单配置
  const { buildFormOptions } = useColumns();
	  // 动态生成表单字段
  const customOptions: CrudOptions = {
    columns: {
      customer_name: {
        title: "姓名",
        type: "text",
				form: {
					rules: [
						{
							required: true,
							message: "请输入姓名",
							trigger: "blur",
						},
					],
				}
      },
      customer_phone: {
        title: "电话",
        type: "text",
				form: {
					rules: [
						{
							required: true,
							message: "请输入电话",
							trigger: "blur",
						},
					],
				}
      },
      payment_method: {
        title: "支付方式",
        type: "dict-select",
				form: {
					rules: [
						{
							required: true,
							message: "请选择支付方式",
							trigger: "change",
						},
					],
				},
				dict: dict({
					data: dictionary('payment_method'),
				}),
      },
			quantity: {
				title: "药品数量",
				type: "number",
				show: false,
				form: {
					show: false,
					rules: [{ required: true, message: "请输入药品数量" }]
				},
				column: {
					show: false,
					component: { name: "fs-values-format" }
				}
			},
    },
    form: {
			col: { span: 24 },
			labelWidth: '100px',
      wrapper: {
        title: "填写订单信息",
				width: '600px',
      },

      async doSubmit({ form }) {
        // console.log("form submit:", form);
        // ElMessage.info("自定义表单提交:" + JSON.stringify(form));
        // ElMessage.warning("抛出异常可以阻止表单关闭");
        // throw new Error("抛出异常可以阻止表单关闭");(selected: any) => ({ medicine_id: selected.id, quantity: 1 })
				console.log(form);
				const data = {
					customer_name: form.customer_name,
					customer_phone: form.customer_phone,
					payment_method: form.payment_method,
					items: selectedIds.value.reduce<{ medicine_id: number, quantity: number }[]>((arr, current: any) => {
						if (form[current.code]) {
							arr.push({ medicine_id: current.id, quantity: form[current.code] })
						}
						return arr
					}, [])
				}
				console.log(data);
				return await api.drugBuyByIdAPI(data)
      }
    }
  }
	const { openDialog } = useFormWrapper();
  //使用crudOptions结构来构建自定义表单配置

  //打开自定义表单
  const openCustomForm = async () => {
		Object.assign(customOptions.columns!, medicine.value)
    const formOptions = buildFormOptions(customOptions);
		console.log(formOptions);
    // index++;
    // formOptions.initialForm = { index };
    // formOptions.newInstance = true; //新实例打开
    const dialogRef = await openDialog(formOptions);
    console.log("openCustomFormRef", dialogRef);
  };



  return {
    openCustomForm,
  };
}




/**
 *
 * @param crudExpose：index传递过来的示例
 * @param context：index传递过来的自定义参数
 * @returns
 */
export const createCrudOptions = function ({ crudExpose, context }: CreateCrudOptionsProps): CreateCrudOptionsRet {
	const { openCustomForm, } = useBuyMedicineFormWrapper(crudExpose);
	const pageRequest = async (query: any) => {
		return await api.infoListAPI(query);
	};
	const editRequest = async ({ form, row }: EditReq) => {
		form.id = row.id;
		return await api.infoEditAPI(form);
	};
	const delRequest = async ({ row }: DelReq) => {
		return await api.infoDelAPI(row.id);
	};
	const addRequest = async ({ form }: AddReq) => {
		return await api.infoAddAPI(form);
	};

	return {
		crudOptions: {
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
			pagination: {
				show: true,
			},
			actionbar: {
				buttons: {
					add: {
						show: auth('drug:info:add'),
					},
					buy: {
						show: true,
						text: '购买',
						click() {
							console.log('buy', context);
							openCustomForm()
						}
					},
				},
			},
			rowHandle: {
				//固定右侧
				fixed: 'right',
				width: computed(() => {
					if (auth('info:AuthorizedAdd') || auth('info:AuthorizedSearch')) {
						return 420;
					}
					return 320;
				}),
				buttons: {
					view: {
						show: false
					},
					edit: {
						show: auth('drug:info:edit'),
					},
					remove: {
						show: auth('drug:info:delete'),
					},
				},
			},
			// form: {
			// 	col: { span: 24 },
			// 	labelWidth: '100px',
			// 	wrapper: {
			// 		is: 'el-dialog',
			// 		width: '600px',
			// 	},
			// },
			table: {
        rowKey: "id", //设置你的主键id， 默认rowKey=id
        onSelectionChange
      },
			columns: {
				$checked: {
          title: "选择",
          form: { show: false },
          column: {
            type: "selection",
            align: "center",
            width: "55px",
            columnSetDisabled: true, //禁止在列设置中选择
          }
        },
				_index: {
					title: '序号',
					form: { show: false },
					column: {
						type: 'index',
						align: 'center',
						width: '70px',
						columnSetDisabled: true, //禁止在列设置中选择
					},
				},
				id: {
					title: 'ID',
					column: { show: false },
					search: { show: false },
					form: { show: false },
				},
				name: {
					title: '名称',
					search: { show: true },
					column: {
						minWidth: 90,
					},
					form: {
						rules: [{ required: true, message: '角色名称必填' }],
						component: {
							placeholder: '请输入角色名称',
						},
					},
				},
				code: {
					title: 'Code',
					search: { show: true },
					column: {
						minWidth: 90,
					},
					form: {
						rules: [{ required: true, message: 'Code必填' }],
						component: {
							placeholder: '请输入Code',
						},
					},
				},
				manufacturer: {
					title: '生产商',
					search: { show: false },
					column: {
						minWidth: 120,
						columnSetDisabled: true,
					},
					form: {
						rules: [{ required: true, message: '生产商必填' }],
						component: {
							placeholder: '输入生产商',
						},
					},
					valueBuilder(context) {
						const { row, key } = context;
						return row[key];
					},
				},
				approval_number: {
					title: '批准文号',
					search: { show: false },
					column: {
						minWidth: 90,
					},
					form: {
						rules: [{ required: true, message: '批准文号必填' }],
						component: {
							placeholder: '输入批准文号',
						},
					},
				},
				category_name: {
					title: '类别',
					search: { show: false },
					type: 'string',
					column: {
						minWidth: 90,
					},
					form: {
						component: {
							name: 'fs-dict-select',
							placeholder: '请选择类别',
							dict: dict({
								url: `/api/drug/medicine/category/?=category=1`
							}),
							transformDictData(list: any[]) {
								return list.map(item => ({
									label: item.name,
									value: item.id
								}))
							},
						},
						rules: [{ required: true, message: '类别必填' }],
					},
					valueResolve(context) {
						const { row, key } = context;
						return row['category'] = row[key];
					},
				},
				price: {
					title: '价格',
					search: { show: false },
					type: 'number',
					column: {
						minWidth: 90,
						sortable: 'custom',
					},
					form: {
						rules: [{ required: true, message: '价格必填' }],
						component: {
							placeholder: '请输入价格',
						}
					},
				},
				stock: {
					title: '库存',
					search: { show: false },
					type: 'number',
					column: {
						minWidth: 90,
						sortable: 'custom',
					},
					form: {
						rules: [{ required: true, message: '库存必填' }],
						component: {
							placeholder: '请输入库存',
						},
					},
				},
				unit: {
					title: '单位',
					search: { show: false },
					type: 'string',
					column: {
						minWidth: 90,
					},
					form: {
						rules: [{ required: true, message: '单位必填' }],
						component: {
							placeholder: '请输入单位',
						}
					},
				},
				description: {
					title: '描述',
					search: { show: false },
					type: 'string',
					column: {
						minWidth: 90,
					},
					form: {
						rules: [{ required: true, message: '类别必填' }],
						component: {
							placeholder: '请输入描述',
						}
					},
				},
				specification: {
					title: '规格',
					search: { show: true },
					type: 'string',
					column: {
						minWidth: 90,
					},
					form: {
						rules: [{ required: true, message: '价格必填' }],
						component: {
							placeholder: '请输入规格',
						}
					},
				},
				status: {
					title: '状态',
					search: { show: true },
					type: 'dict-radio',
					column: {
						width: 100,
						component: {
							name: 'fs-dict-switch',
							activeValue: 1,
							inactiveValue: 0,
							style: '--el-switch-on-color: var(--el-color-primary); --el-switch-off-color: #dcdfe6',
							onChange: compute((context) => {
								return () => {
									api.infoEditAPI(context.row).then((res: APIResponseData) => {
										successMessage(res.msg as string);
									});
								};
							}),
						},
					},
					dict: dict({
						value: dictionary('drug_info_status'),
					}),
					form: {
						component: {
							name: 'fs-dict-switch',
							activeText: '启用',
							inactiveText: '禁用',
							activeValue: 1,
							inactiveValue: 0,
						}
					}
				},
			},
		},
		selectedIds
	};
};
